package servlet;

import com.alibaba.fastjson.JSON;
import entity.*;
import service.IUserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet(name = "ls", urlPatterns = {"/login"})
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("get....");
        request.setCharacterEncoding("utf-8");
//        String username = request.getParameter("un");//获取表单输入框的文字
//        String password = request.getParameter("pwd");
        //接受数据
        BufferedReader reader = request.getReader();
        String userstr = reader.readLine();
        User user1 = JSON.parseObject(userstr, User.class);
        String username = user1.getUsername();
        String password = user1.getPassword();
        System.out.println(username);
        System.out.println(password);

        IUserService us = new UserServiceImpl();
        User loginUser = us.login(username, password);

        System.out.println(loginUser);

        HttpSession session = request.getSession();//获取浏览器会话
        session.setAttribute("lu", loginUser);//把登录用户保存到session中

        Map<Product, Integer> shoppingcar = new HashMap<>();//创建购物车对象
        session.setAttribute("sc", shoppingcar);//把购物车保存到session中

//        response.sendRedirect("login_result.jsp");//重定向到下一页面(JSP)
//        response.sendRedirect("product_list.jsp");//不能直接重定向到jsp
//        response.sendRedirect("show_products");//要先重定向到servlet，再由servlet转发到jsp
        if (loginUser != null) {
            Cookie userCookie = new Cookie("username", username);
            response.addCookie(userCookie);
            response.getWriter().write("sucess");
        } else {
            response.getWriter().write("false");
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("post...");
        this.doGet(request, response);
    }
}
